import React, { useEffect, useState } from 'react';
import { Card, Input, Select, List, Space, Tag, Image, Pagination, Empty } from 'antd';
import { useNavigate } from 'react-router-dom';
import { getMedicineList, getMedicineCategoryList } from '@/api/medicine';
import type { MedicineDTO, MedicineCategoryDTO } from '@/types/medicine';
import styles from './styles.module.less';

const { Search } = Input;
const { Option } = Select;

const MedicineList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [keyword, setKeyword] = useState('');
  const [categoryId, setCategoryId] = useState<number>();
  const [categories, setCategories] = useState<MedicineCategoryDTO[]>([]);
  const [list, setList] = useState<MedicineDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取药品分类
  const fetchCategories = async () => {
    try {
      const res = await getMedicineCategoryList();
      setCategories(res.data.data);
    } catch (error) {
      console.error('获取药品分类失败:', error);
    }
  };

  // 获取药品列表
  const fetchMedicines = async (page = current) => {
    setLoading(true);
    try {
      const res = await getMedicineList({
        keyword,
        categoryId,
        page,
        size: pageSize,
      });
      setList(res.data.data.list);
      setTotal(res.data.data.total);
      setCurrent(page);
    } catch (error) {
      console.error('获取药品列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    fetchMedicines(1);
  }, [keyword, categoryId, pageSize]);

  const handleSearch = (value: string) => {
    setKeyword(value);
  };

  const handleCategoryChange = (value: number) => {
    setCategoryId(value);
  };

  const handlePageChange = (page: number, size?: number) => {
    if (size && size !== pageSize) {
      setPageSize(size);
      return;
    }
    fetchMedicines(page);
  };

  const renderListItem = (item: MedicineDTO) => {
    const images = item.images?.split(',').filter(Boolean) || [];
    const firstImage = images[0];

    return (
      <List.Item
        key={item.id}
        className={styles.listItem}
        onClick={() => navigate(`/medicine/detail/${item.id}`)}
      >
        <div className={styles.content}>
          <div className={styles.body}>
            {firstImage && (
              <div className={styles.image}>
                <Image
                  src={firstImage}
                  alt={item.name}
                  width={200}
                  height={150}
                  fallback="/images/fallback.png"
                />
              </div>
            )}
            <div className={styles.info}>
              <div className={styles.header}>
                <h3 className={styles.title}>{item.name}</h3>
                <Tag color="blue">{item.categoryName}</Tag>
                <Tag color="green">￥{item.price?.toFixed(2)}</Tag>
              </div>
              {item.manufacturer && (
                <div className={styles.section}>
                  <strong>生产厂家：</strong>
                  <p>{item.manufacturer}</p>
                </div>
              )}
              {item.specification && (
                <div className={styles.section}>
                  <strong>规格：</strong>
                  <p>{item.specification}</p>
                </div>
              )}
              {item.description && (
                <div className={styles.section}>
                  <strong>描述：</strong>
                  <p>{item.description}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </List.Item>
    );
  };

  return (
    <Card className={styles.medicineList}>
      <div className={styles.header}>
        <Space size="large">
          <Search
            placeholder="搜索药品名称、生产厂家"
            allowClear
            enterButton
            style={{ width: 300 }}
            onSearch={handleSearch}
          />
          <Select
            placeholder="选择药品分类"
            allowClear
            style={{ width: 200 }}
            onChange={handleCategoryChange}
          >
            {categories.map(category => (
              <Option key={category.id} value={category.id}>
                {category.name}
              </Option>
            ))}
          </Select>
        </Space>
      </div>

      <List
        className={styles.list}
        dataSource={list}
        renderItem={renderListItem}
        loading={loading}
        locale={{
          emptyText: <Empty description="暂无相关药品" />,
        }}
      />

      <div className={styles.pagination}>
        <Pagination
          current={current}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={handlePageChange}
        />
      </div>
    </Card>
  );
};

export default MedicineList; 